<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表表格数据区域 -->
      <el-table :data="usersList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改用户信息按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click=" showEditDialog(scope.row.id) "
            ></el-button>
            <!-- 删除用户按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeUserId(scope.row.id)"
            ></el-button>
            <!-- 分配用户角色按钮 -->
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="setRole(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 用户列表分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <!-- 添加用户对话框标题 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDiaLogClosed">
      <!-- 添加用户主体区域 -->
      <el-form :model="addForm" :rules="addFromRules" ref="addFormRef" label-width="80px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="email" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 添加用户对话框页脚区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="提示" :visible.sync="EditDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 修改用户表单 -->
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名称">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 修改用户页脚 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配用户角色对话框 -->
    <el-dialog title="提示" :visible.sync="setRoleDialogVisible" width="50%" @close = "roleDialogClosed" >
      <div>
        <p>当前的用户：{{ roleInfo.username}}</p>
        <P>当前的角色：{{ roleInfo.role_name}}</P>
        <!-- 分配角色下拉列表框 -->
        <p>
          分配用户角色：
          <el-select v-model="selectdValueId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "UserList",
  data() {
    // 自定义邮箱的验证规则
    var checkEmail = (rule, value, callback) => {
      var regExp = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (!regExp.test(value)) {
        callback(new Error("请填入正确的邮箱"));
      }
      callback();
    };
    var checkMobile = (rule, value, callback) => {
      var regExp = /^((0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?)$|^(0?[1][3578][0-9]{9})$|^(400[0-9]{7})$/;
      if (!regExp.test(value)) {
        callback(new Error("请填入正确的手机号码"));
      }
      callback();
    };
    return {
      //获取用户列表数据参数
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      usersList: [],
      total: 0,
      //添加用户对话框的隐藏和显示
      addDialogVisible: false,
      //添加用户对话框的数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //添加用户对话框的验证规则
      addFromRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到  10个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到  10个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      //修改用户表单验证规则
      editRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      //修改用户对话框显示与隐藏属性
      EditDialogVisible: false,
      //修改用户表单信息数据
      editForm: {
        id: "",
        username: "",
        mobile: "",
        email: ""
      },
      //分配用户角色显示与隐藏对话框属性
      setRoleDialogVisible: false,
      //用户信息
      roleInfo: {},
      //角色列表属性
      roleList: [],
      //分配角色选中的Id 值
       selectdValueId:''
    };
  },
  created() {
    //获取用户列表数据方法
    this.getUserList();
  },
  methods: {
    //获取用户列表数据方法
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });

      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.usersList = res.data.users;
      this.total = res.data.total;
    },
    //改变每页显示的条数的方法
    handleSizeChange(newPageSize) {
      this.queryInfo.pagesize = newPageSize;
      this.getUserList();
    },
    //改变当前页的方法
    handleCurrentChange(newPageNum) {
      this.queryInfo.pagenum = newPageNum;
      this.getUserList();
    },
    async userStateChanged(userStated) {
      const { data: res } = await this.$http.put(
        `users/${userStated.id}/state/${userStated.mg_state}`
      );

      if (res.meta.status !== 200) {
        userStated.mg_state = !userStated.mg_state;
        this.$message.error("更新用户状态失败");
      }
      this.$message.success(res.meta.msg);
    },
    //关闭添加用户对话框重置表单
    addDiaLogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status != 201) return this.$message.error("添加用户失败");
        this.$message.success("添加用户成功");
        this.addDialogVisible = false;
        this.getUserList();
      });
    },

    async showEditDialog(id) {
      this.EditDialogVisible = true;
      const { data: res } = await this.$http.get("users/" + id);
      console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("修改用户信息失败");
      this.editForm.username = res.data.username;
      this.editForm.email = res.data.email;
      this.editForm.mobile = res.data.mobile;
      this.editForm.id = res.data.id;
    },
    //修改用户信息对话框重置表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //修改用户信息对话框提交按钮
    EditUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          this.editForm
        );
        if (res.meta.status != 200)
          return this.$message.error("修改用户信息失败");
        this.getUserList();
        this.EditDialogVisible = false;
        this.$message.success("修改用户信息成功");
      });
    },
    //删除用户方法
    async removeUserId(id) {
      const confirmTxt = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);

      if (confirmTxt != "confirm")
        return this.$message.info("取消用户删除操作");

      const { data: res } = await this.$http.delete("users/" + id);

      if (res.meta.status != 200) {
        this.$message.info("删除用户失败");
      }

      this.getUserList();
      this.$message.success("删除用户成功");
    },
    //分配用户角色按钮方法
    async setRole(roleInfo) {
    
      this.roleInfo = roleInfo;
      //获取用户角色列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200)
        return this.$message.error("获取角色列表失败");
      
      this.roleList = res.data;
      this.setRoleDialogVisible = true;
    },
  //分配用户角色成功方法
    async saveRoleDialog(){
      if(!this.selectdValueId){
        this.$message.error("请选择角色")
      }
      const  {data:res} = await this.$http.put(`users/${this.roleInfo.id}/role`,{
        rid:this.selectdValueId
      })
      
       if(res.meta.status != 200) return this.$message.error("分配角色列表失败")

        this.getUserList();
        this.$message.success("分配用户角色成功")
        this.setRoleDialogVisible = false;
    },
  // 重置关闭分配角色对话框
    roleDialogClosed(){
      this.selectdValueId = "";
      this.roleList = "";
    }
  }
};
</script>

<style lang="less" scoped></style>